package org.jflame.devAide.component;

import org.jflame.commons.util.file.FileHelper;

import java.io.File;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import javafx.beans.property.ObjectProperty;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;

/**
 * 图片文件选择器
 * 
 * @author charles.zhang
 */
public class ImageChooser extends VBox {

    private Button fileButton;
    private FileChooser fileChooser = new FileChooser();
    private SelectionMode selectionMode = SelectionMode.SINGLE;// 是否可多选择文件
    private ObjectProperty<List<File>> selectedFileProperty;
    private TilePane thumbnailPane;

    private final String[] supportedImageTypes = { "jpg","jpeg","png","gif","bmp" };

    public ImageChooser() {
        getStyleClass().add("image-chooser");
        fileChooser.setSelectedExtensionFilter(new ExtensionFilter("", supportedImageTypes));
        thumbnailPane = new TilePane();
        thumbnailPane.getStyleClass()
                .add("thumbnail-pane");

        fileButton = new Button("选择图片");
        Label lblTip = new Label("可拖放文件到这里");
        getChildren().addAll(thumbnailPane, fileButton, lblTip);

        setOnDragOver(new EventHandler<DragEvent>() {

            @Override
            public void handle(DragEvent event) {
                Dragboard dragboard = event.getDragboard();
                if (dragboard.hasFiles()) {
                    File tmpFile = dragboard.getFiles()
                            .get(0);
                    String ext = FileHelper.getExtension(tmpFile.getName(), false);
                    if (ArrayUtils.contains(supportedImageTypes, ext)) {
                        event.acceptTransferModes(TransferMode.ANY);
                    }
                }
                event.consume();
            }
        });

        setOnDragDropped(new EventHandler<DragEvent>() {

            @Override
            public void handle(DragEvent event) {

            }
        });
    }

    public SelectionMode getSelectionMode() {
        return selectionMode;
    }

    public void setSelectionMode(SelectionMode selectionMode) {
        this.selectionMode = selectionMode;
    }
}
